package com.lifang.framework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.TypeUtil;
import com.lifang.framework.beans.BeansException;
import com.lifang.framework.beans.factory.*;
import com.lifang.framework.beans.factory.config.AutowireCapableBeanFactory;
import com.lifang.framework.beans.factory.config.BeanPostProcessor;
import com.lifang.framework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import com.lifang.framework.beans.factory.config.InstantiationStrategy;
import com.lifang.framework.core.convert.ConversionService;
import com.lifang.framework.util.ClassUtils;
import com.lifang.framework.util.ConstructorUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * 默认抽象bean装配（ioc）工厂
 */
@Slf4j
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {

    /**
     * 类加载器
     */
    private final ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

    /**
     * 返回类加载器
     */
    public ClassLoader getBeanClassLoader() {
        return beanClassLoader;
    }

    /**
     * 装配策略
     * cglib 或者 jdk反射
     */
    private final InstantiationStrategy instantiationStrategy = new JdkInstantiationStrategy();

    /**
     * 返回类装配策略
     */
    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    /**
     * 创建bean
     */
    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean = resolveBeforeInstantiation(beanName, beanDefinition);
        if (bean != null) {
            return registerSingletonBean(beanName, bean, beanDefinition);
        }
        return doCreateBean(beanName, beanDefinition, args);
    }

    /**
     * 执行创建Bean的流程
     */
    protected Object doCreateBean(String beanName, BeanDefinition beanDefinition, Object[] args) {
        try {
            // 创建Bean实例
            Object bean = createBeanInstance(beanDefinition, beanName, args);

            // 完成Bean的初始化操作,如Aware感知方法、初始化方法等等
            return initializeBean(beanName, bean, beanDefinition);
        } catch (Throwable th) {
             throw new BeansException("Instantiation of bean " + beanDefinition.getBeanClass().getName() + " failed,nesting exception is " + th.getMessage());
        }
    }

    /**
     * 创建Bean实例
     */
    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) {
        // beanClass检查
        Class<?> beanClass = beanDefinition.getBeanClass();
        if (!Modifier.isPublic(beanClass.getModifiers())) {
            throw new BeansException("Bean class isn't public beanName: " + beanClass.getName());
        }
        if (beanClass.isInterface()) {
            throw new BeansException(beanClass.getName() + " class is an interface");
        }

        // 构造方法解析，存入
        Constructor<?> constructor;
        if (beanDefinition.isConstructorArgumentsResolved()) {
            constructor = (Constructor<?>) beanDefinition.getResolvedConstructorOrFactoryMethod();
        } else {
            constructor = ConstructorUtil.findFitConstructor(beanDefinition, args);
            beanDefinition.setResolvedConstructorOrFactoryMethod(constructor);
            beanDefinition.setConstructorArgumentsResolved(Boolean.TRUE);
        }

        Object bean = getInstantiationStrategy().instantiation(beanDefinition, beanName, constructor, args);

        // 提前暴露Bean对象，用于解决循环依赖
        if (beanDefinition.isSingleton() || isSingletonCurrentlyInCreation(beanName)) {
            final Object exposeBean = bean;
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, beanDefinition, exposeBean));
        }

        // 记录当前正在创建Bean的名称
        if (beanDefinition.isSingleton()) {
            beforeSingletonCreation(beanName);
        } else if (beanDefinition.isPrototype()) {
            beforePrototypeCreation(beanName);
        }

        // 是否继续执行,返回false可阻止自动赋值等
        if (isHasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor postProcessor : getBeanPostProcessors()) {
                if (postProcessor instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor instantiationProcessor = (InstantiationAwareBeanPostProcessor) postProcessor;
                    if (!instantiationProcessor.postProcessAfterInstantiation(bean, beanName)) {
                        return bean;
                    }
                }
            }
        }

        // 注册销毁钩子方法
        registerDisposableBeanIfNecessary(beanName, bean, beanDefinition);

        // 填充属性
        populateBean(beanName, beanDefinition, bean);

        return bean;
    }

    /**
     * 给Bean填充属性
     */
    private void populateBean(String beanName, BeanDefinition beanDefinition, Object bean) {

        // 寻找或构建合适的PropertyValues
        PropertyValues propertyValues = beanDefinition.getPropertyValues();
        if (isHasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
                if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor iBeanPostProcessor = (InstantiationAwareBeanPostProcessor) beanPostProcessor;
                    PropertyValues pvsToUse = iBeanPostProcessor.postProcessProperties(propertyValues, bean, beanName);
                    if (pvsToUse == null) {
                        break;
                    }
                    propertyValues = pvsToUse;
                }
            }
        }

        // 给字段填充属性
        if (propertyValues != null) {
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                try {
                    String name = propertyValue.getName();
                    Object value = propertyValue.getValue();
                    if (value instanceof BeanReference) {
                        BeanReference beanReference = (BeanReference) value;
                        value = getBean(beanReference.getBeanName());
                    } else {
                        Class<?> sourceType = value.getClass();
                        Class<?> targetType = (Class<?>) TypeUtil.getFieldType(bean.getClass(), name);
                        ConversionService conversionService = getConversionService();
                        if (conversionService != null) {
                            if (conversionService.canConvert(sourceType, targetType)) {
                                value = conversionService.convert(value, targetType);
                            }
                        }
                    }
                    BeanUtil.setFieldValue(bean, name, value);
                } catch (Exception ex) {
                    throw new BeansException("Error setting property values：" + beanName);
                }
            }
        }
    }

    protected Object getEarlyBeanReference(String beanName, BeanDefinition beanDefinition, Object bean) {
        Object exposedObject = bean;
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
                exposedObject = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).getEarlyBeanReference(bean, beanDefinition, beanName);
            }
        }
        return exposedObject;
    }

    /**
     * 注册单例bean
     */
    protected Object registerSingletonBean(String beanName, Object bean, BeanDefinition beanDefinition) {
        Object exposedObject = bean;
        if (beanDefinition.isSingleton()) {
            Object singleton = getSingleton(beanName);
            if (singleton != null) {
                exposedObject = singleton;
            }
        }
        registerSingleton(beanName, exposedObject);
        return exposedObject;
    }

    /**
     * 解析bean，存在BeanPostProcessor提前实例化Bean
     * 一般用于接口代理等
     */
    protected Object resolveBeforeInstantiation(String beanName, BeanDefinition beanDefinition) {
        Object bean = null;
        if (isHasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
                if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
                    Object result = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessBeforeInstantiation(beanDefinition.getBeanClass(), beanName);
                    if (result != null) {
                        bean = result;
                    }
                }
            }
            if (bean != null) {
                for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
                    if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
                        bean = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessAfterInstantiation(bean, beanName);
                    }
                }
            }
        }
        return bean;
    }

    /**
     * 初始化bean
     */
    private Object initializeBean(String beanName, Object bean, BeanDefinition beanDefinition) {
        // 调用Aware感知方法
        invokeAwareMethods(beanName, bean);

        // 执行 BeanPostProcessor Before 处理
        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);

        // 调用初始化方法
        try {
            invokeInitMethods(beanName, wrappedBean, beanDefinition);
        } catch (Exception ex) {
            throw new BeansException("Invocation of init method of bean " + beanName + " failed, nesting exception is" + ex.getMessage());
        }

        // 执行 BeanPostProcessor After 处理
        wrappedBean = applyBeanPostProcessorsAfterInitialization(bean, beanName);

        if (beanDefinition.isSingleton()) {
            registerSingleton(beanName, wrappedBean);
            afterSingletonCreation(beanName);
        } else {
            afterPrototypeCreation(beanName);
        }

        return wrappedBean;
    }

    /**
     * 调用Aware感知方法
     */
    private void invokeAwareMethods(String beanName, Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
            }
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(this);
            }
        }
    }

    /**
     * 执行bean初始化方法
     */
    private void invokeInitMethods(String beanName, Object wrappedBean, BeanDefinition beanDefinition) throws Exception {
        // 如果bean实现了InitializingBean接口 调用其afterPropertiesSet方法
        if (wrappedBean instanceof InitializingBean) {
            ((InitializingBean) wrappedBean).afterPropertiesSet();
        }

        // 调用bean执行器初始化方法
        String initMethodName = beanDefinition.getInitMethodName();
        if (StrUtil.isNotEmpty(initMethodName) && !(wrappedBean instanceof InitializingBean)) {
            Method initMethod = ClassUtil.getDeclaredMethod(beanDefinition.getBeanClass(), initMethodName);
            if (initMethod == null) {
                throw new BeansException("Could not find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'");
            }
            for (Method method : wrappedBean.getClass().getMethods()) {
                if (StrUtil.equals(beanDefinition.getInitMethodName(), method.getName())) {
                    if (method.getParameterCount() > 0) {
                        throw new BeansException("Init method Cannot have parameters " + wrappedBean.getClass().getName());
                    }
                    try {
                        method.invoke(wrappedBean);
                    } catch (IllegalArgumentException exception) {
                        throw new BeansException(beanName + " init method Cannot have parameters");
                    }
                }
            }
        }
    }

    /**
     * 执行 Bean增强器 的before 方法，如遇到null，会停止执行
     */
    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(result, beanName);
            if (null == current) {
                return result;
            }
            result = current;
        }
        return result;
    }

    /**
     * 执行 Bean增强器 的after 方法，如遇到null，会停止执行
     */
    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(existingBean, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }

    /**
     * 注册销毁钩子方法
     */
    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, BeanDefinition beanDefinition) {
        if (beanDefinition.isSingleton()) {
            if (StrUtil.isNotEmpty(beanDefinition.getDestroyMethodName())) {
                registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, beanDefinition));
            } else if (bean instanceof DisposableBean) {
                beanDefinition.setDestroyMethodName("destroy");
                registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, beanDefinition));
            }
        }
    }
}
